<template>
  <div class="work-report-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Tickets /></el-icon>
          <span>报工质检</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Histogram /></el-icon>
          <span>报工质检记录</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline class="filter-form" @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.reportKeyword" clearable placeholder="请输入检验单名称/号" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.orderKeyword" clearable placeholder="请输入工单名称/编号" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.taskKeyword" clearable placeholder="请输入任务名称/编号" />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            clearable
            placeholder="请选择状态"
            class="w-180"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.inspector"
            clearable
            placeholder="请选择检验人"
            class="w-180"
          >
            <el-option
              v-for="item in inspectorOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-dropdown>
            <el-button class="more-btn">
              更多
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="ElMessage.info('示例：导出选中报工')">
                  导出
                </el-dropdown-item>
                <el-dropdown-item @click="ElMessage.info('示例：列配置')">
                  列配置
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="handleAction('新增')">新增</el-button>
        <el-button type="success" plain @click="handleAction('质检')">质检</el-button>
        <el-button type="warning" plain @click="handleAction('导出')">导出</el-button>
      </div>

      <el-table
        class="report-table"
        border
        stripe
        height="640"
        :data="rows"
        :loading="loading"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" fixed="left" />
        <el-table-column type="index" label="序号" width="70" align="center" fixed="left" />
        <el-table-column
          prop="inspectionName"
          label="检验单名称"
          min-width="160"
          fixed="left"
          show-overflow-tooltip
        />
        <el-table-column prop="inspectionCode" label="检验单号" min-width="150" fixed="left" />

        <el-table-column prop="orderName" label="工单名称" min-width="160" />
        <el-table-column prop="taskName" label="任务名称" min-width="150" />
        <el-table-column prop="siteName" label="站点名称" min-width="140" />
        <el-table-column prop="processName" label="工序名称" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="160" />
        <el-table-column prop="productCode" label="产品编号" min-width="140" />
        <el-table-column prop="teamName" label="班组名称" min-width="140" />
        <el-table-column prop="taskOwner" label="任务负责人" min-width="140" />
        <el-table-column prop="reportUser" label="报工人员" min-width="140" />
        <el-table-column prop="reportQty" label="报工数量" min-width="120" />
        <el-table-column prop="reportTime" label="报工时间" min-width="160" />
        <el-table-column prop="inspectionTime" label="检验时间" min-width="160" />
        <el-table-column prop="inspectionType" label="检验类型" min-width="140" />
        <el-table-column prop="inspectionDept" label="检验部门" min-width="140" />
        <el-table-column prop="inspector" label="检验人" min-width="130" />
        <el-table-column prop="checkQty" label="检测数量" min-width="120" />
        <el-table-column prop="qualifiedQty" label="合格数量" min-width="120" />
        <el-table-column prop="unqualifiedQty" label="不合格数量" min-width="120" />
        <el-table-column prop="qualifiedRate" label="合格率" min-width="120" />
        <el-table-column prop="result" label="检测结果" min-width="130" />

        <el-table-column label="状态" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-tag :type="statusTag(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleRowAction('质检', scope.row)">
              质检
            </el-button>
            <el-divider direction="vertical" />
            <el-button link type="danger" @click="handleRowAction('删除', scope.row)">
              删除
            </el-button>
            <el-divider direction="vertical" />
            <el-button link @click="handleRowAction('查看', scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowDown, ArrowRight, Histogram, HomeFilled, Tickets } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

interface WorkReportItem {
  id: number
  inspectionName: string
  inspectionCode: string
  orderName: string
  taskName: string
  siteName: string
  processName: string
  productName: string
  productCode: string
  teamName: string
  taskOwner: string
  reportUser: string
  reportQty: number
  reportTime: string
  inspectionTime: string
  inspectionType: string
  inspectionDept: string
  inspector: string
  checkQty: number
  qualifiedQty: number
  unqualifiedQty: number
  qualifiedRate: string
  result: string
  status: string
}

const router = useRouter()
const loading = ref(false)
const allRows = ref<WorkReportItem[]>([])
const rows = ref<WorkReportItem[]>([])
const selections = ref<WorkReportItem[]>([])

const pager = reactive({
  page: 1,
  size: 10,
  total: 0
})

const searchForm = reactive({
  reportKeyword: '',
  orderKeyword: '',
  taskKeyword: '',
  status: '',
  inspector: ''
})

const statusOptions = [
  { label: '未质检', value: '未质检' },
  { label: '质检中', value: '质检中' },
  { label: '已质检', value: '已质检' },
  { label: '已关闭', value: '已关闭' }
]

const inspectorOptions = computed(() => {
  const set = new Set(allRows.value.map(item => item.inspector))
  return Array.from(set)
})

const fetchList = () => {
  loading.value = true
  setTimeout(() => {
    const dataset = generateMockReports()
    allRows.value = dataset
    applyFilters()
    loading.value = false
  }, 200)
}

const applyFilters = () => {
  let data = [...allRows.value]

  if (searchForm.reportKeyword.trim()) {
    const kw = searchForm.reportKeyword.trim()
    data = data.filter(
      item => item.inspectionName.includes(kw) || item.inspectionCode.includes(kw)
    )
  }

  if (searchForm.orderKeyword.trim()) {
    const kw = searchForm.orderKeyword.trim()
    data = data.filter(item => item.orderName.includes(kw))
  }

  if (searchForm.taskKeyword.trim()) {
    const kw = searchForm.taskKeyword.trim()
    data = data.filter(item => item.taskName.includes(kw))
  }

  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }

  if (searchForm.inspector) {
    data = data.filter(item => item.inspector === searchForm.inspector)
  }

  pager.total = data.length
  const start = (pager.page - 1) * pager.size
  rows.value = data.slice(start, start + pager.size)
}

const handleSearch = () => {
  pager.page = 1
  applyFilters()
}

const handleReset = () => {
  Object.assign(searchForm, {
    reportKeyword: '',
    orderKeyword: '',
    taskKeyword: '',
    status: '',
    inspector: ''
  })
  pager.page = 1
  applyFilters()
}

const onSelectionChange = (val: WorkReportItem[]) => {
  selections.value = val
}

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  applyFilters()
}

const onPageChange = (page: number) => {
  pager.page = page
  applyFilters()
}

const handleAction = (action: string) => {
  if (!selections.value.length && action !== '新增') {
    ElMessage.warning('请先选择数据')
    return
  }
  ElMessage.info(`${action}操作示例`)
}

const handleRowAction = (action: string, row: WorkReportItem) => {
  if (action === '查看') {
    console.log('准备跳转到详情页面，ID:', row.id)
    try {
      router.push({ 
        name: 'WorkReportDetail', 
        query: { id: String(row.id) } 
      })
    } catch (error) {
      console.error('路由跳转错误:', error)
      ElMessage.error('跳转失败: ' + (error as Error).message)
    }
  } else {
    ElMessage.info(`${action} - ${row.inspectionCode}`)
  }
}

const statusTag = (status: string) => {
  switch (status) {
    case '质检中':
      return 'warning'
    case '未质检':
      return 'info'
    case '已质检':
      return 'success'
    case '已关闭':
      return 'danger'
    default:
      return ''
  }
}

function generateMockReports(): WorkReportItem[] {
  const statuses = ['未质检', '质检中', '已质检', '已关闭']
  const inspectors = ['刘勇', '赵敏', '陈倩', '李辉']
  const taskOwners = ['刘主任', '李主管', '赵工', '周班长']
  const reporters = ['赵子龙', '孙策', '周瑜', '黄盖']
  const inspectionTypes = ['首检', '巡检', '终检']

  return Array.from({ length: 40 }).map((_, idx) => {
    const plan = 50 + idx * 2
    const checkQty = plan - (idx % 6)
    const qualifiedQty = checkQty - (idx % 4)
    const unqualifiedQty = Math.max(checkQty - qualifiedQty, 0)
    const inspector = inspectors[idx % inspectors.length] ?? inspectors[0]!
    const status = statuses[idx % statuses.length] ?? statuses[0]!
    const inspectionType = inspectionTypes[idx % inspectionTypes.length] ?? inspectionTypes[0]!

    return {
      id: idx + 1,
      inspectionName: `任务检验单-${idx + 1}`,
      inspectionCode: `JYDH${(2010 + idx).toString().padStart(4, '0')}`,
      orderName: `新品工单-${(idx % 3) + 1}`,
      taskName: `工单任务${(idx % 5) + 1}`,
      siteName: `站点${(idx % 4) + 1}`,
      processName: `工序${['一', '二', '三'][idx % 3]}`,
      productName: `新产品${(idx % 4) + 1}`,
      productCode: `CPBH${(2150 + idx).toString()}`,
      teamName: `班组${['一', '二', '三'][idx % 3]}`,
      taskOwner: taskOwners[idx % taskOwners.length] ?? taskOwners[0]!,
      reportUser: reporters[idx % reporters.length] ?? reporters[0]!,
      reportQty: plan,
      reportTime: `2025-11-${(idx % 9) + 18} 08:${(idx % 6).toString().padStart(2, '0')}`,
      inspectionTime: `2025-11-${(idx % 9) + 18} 10:${(idx % 6).toString().padStart(2, '0')}`,
      inspectionType,
      inspectionDept: `质检部${(idx % 2) + 1}`,
      inspector,
      checkQty,
      qualifiedQty,
      unqualifiedQty,
      qualifiedRate: `${((qualifiedQty / (checkQty || 1)) * 100).toFixed(1)}%`,
      result: qualifiedQty === checkQty ? '合格' : '不合格',
      status
    }
  })
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.work-report-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 4px;
}

.breadcrumb-container {
  background: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(64, 90, 182, 0.08);
}

.breadcrumb-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #7c89a3;
}

.breadcrumb-item.active span {
  color: #2f54eb;
  font-weight: 600;
}

.breadcrumb-icon {
  color: #6c7fd8;
}

.filter-card,
.table-card {
  border-radius: 12px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.report-table {
  font-size: 13px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}

.w-180 {
  width: 180px;
}

.more-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
</style>

